package com.sgb.kjwl.viewmodel.pick;

import android.content.Intent;

import androidx.databinding.ObservableField;

import com.chuanglan.shanyan_sdk.OneKeyLoginManager;




import com.sgb.kjwl.AppConstant;
import com.sgb.kjwl.api.APIManager;
import com.swgk.core.base.api.ICallBack;

import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.pick.ApplicationQuotationEntity;
import com.sgb.kjwl.model.entity.pick.EnterpriseBiddingDetailEntity5;
import com.sgb.kjwl.model.entity.pick.EnterpriseBiddingJoinEntity5;
import com.sgb.kjwl.model.entity.transport.MapLongAndLatEntity;
import com.sgb.kjwl.model.entity.user.AddMachineOutEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.model.entity.user.OneKeyLoginEntity;
import com.sgb.kjwl.repository.PickRepertory;
import com.sgb.kjwl.view.ui.activity.pick.EnterpriseBiddingActivity5;
import com.sgb.kjwl.view.ui.activity.self.userInfo.SetPwdActivity;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.im.immodel.IMUtils;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class EnterpriseBiddingModel5 extends BaseViewModel {

    public ObservableField<ApplicationQuotationEntity> applicationQuotationEntity = new ObservableField<>(new ApplicationQuotationEntity());
    public ObservableField<AddMachineOutEntity> addMachineOutEntity = new ObservableField<>(new AddMachineOutEntity());

    private PickRepertory repertory;
    private EnterpriseBiddingActivity5 activity;

    public EnterpriseBiddingModel5(EnterpriseBiddingActivity5 actity, PickRepertory repertory) {
        this.activity = actity;
        this.repertory = repertory;
    }

    /**
     * 获取投标人报名信息
     *
     * @param businessNo
     * @param tenderingApplyType 1.报名2.投标3.报名申请/投标申请4.竞价
     */
    public void findTenderApply(String businessNo, int tenderingApplyType) {
        DialogHelper.showProgressDialog(activity, null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
        Map map = new HashMap();
        map.put("businessNo", businessNo);//"1254687498173100034"
        map.put("tenderingApplyType", tenderingApplyType);//"1254687498173100034"
        String localLng = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LONGITUDE_ID, "");
        String localLat = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, "");
        map.put("localLng", localLng);
        map.put("localLat", localLat);

        APIManager.getInstance().getPickAPI().findTenderApply(map).enqueue(new ICallBack<BaseEntity<EnterpriseBiddingDetailEntity5>>() {
            @Override
            public void onSuccess(BaseEntity<EnterpriseBiddingDetailEntity5> data) {
                if (data == null) return;
                if (data.getState() == null) return;
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    activity.setDetailData(data.getData());
                } else {
                    MToast.showToast(activity, data.getMsg());
                }
            }
        });
    }



    /**
     * 普通报价
     */
    public void saveApply(EnterpriseBiddingJoinEntity5 enterpriseBiddingEntity) {
        DialogHelper.showProgressDialog(activity, null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUploadAPI().saveApply(enterpriseBiddingEntity).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.addSucc();
                } else {
                    MToast.showToast(activity, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                t.printStackTrace();
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    /**
     * 竞价
     *
     * @param enterpriseBiddingJoinEntity5
     */
    public void publishBidding(EnterpriseBiddingJoinEntity5 enterpriseBiddingJoinEntity5) {
        DialogHelper.showProgressDialog(activity, null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUploadAPI().publishBidding(enterpriseBiddingJoinEntity5).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.addSucc();
                } else {
                    MToast.showToast(activity, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                t.printStackTrace();
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    /**
     * 新增申请报名信息
     */
    public void addTenderBidApply(EnterpriseBiddingJoinEntity5 enterpriseBiddingEntity) {
        DialogHelper.showProgressDialog(activity, null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUploadAPI().addTenderBidApply(enterpriseBiddingEntity).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                if (data == null) {
                    return;
                }
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    activity.addSucc();
                }
            }
        });
    }

    /**
     * 投标人提交报名信息
     */
    public void saveApplyForEasy(EnterpriseBiddingJoinEntity5 enterpriseBiddingEntity) {
        DialogHelper.showProgressDialog(activity, null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUploadAPI().saveApplyForEasy(enterpriseBiddingEntity).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                if (data == null) {
                    return;
                }
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    activity.addSucc();
                }
            }
        });
    }

    //提交
    public void saveCompanyBidding(EnterpriseBiddingJoinEntity5 enterpriseBiddingEntity) {
        DialogHelper.showProgressDialog(activity, null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getPickAPI().saveCompanyBidding3(enterpriseBiddingEntity).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.addSucc();
                } else {
                    MToast.showToast(activity, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                t.printStackTrace();
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    //上传多图片
    public void uploadMutiFileModel(File file, int type, int completeNum) {
        Map<String, RequestBody> photos = new HashMap<>();
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        photos.put("file" + "\"; filename=\"" + completeNum + "image.jpg\"", requestBody);
        DialogHelper.showProgressDialog(activity, null, "图片上传中" + completeNum + "/" + 1 + "...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUploadAPI().uploadFile(photos).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.uploadImgSuccess(response.body().getData().toString());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(activity, t.getMessage());
            }
        });
    }

    public void getAddressModel(boolean isShow) {
        if (isShow) {
            DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        }
        APIManager.getInstance().getGoodsAPI().getCityList().enqueue(new Callback<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> call, Response<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> response) {
                if (isShow) {
                    DialogHelper.dismissProgressDialog();
                }
                if (response.body().getCode().equals("200"))
                    activity.showAddressPop(response.body().getData());
            }

            @Override
            public void onFailure(Call<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> call, Throwable t) {
                if (isShow) {
                    DialogHelper.dismissProgressDialog();
                }
                MLog.d(AppConstant.API_LOG, "error " + t.getMessage());
            }
        });
    }

    //获取经纬度信息
    public void getLocationLL(String provinceNo, String cityNo, String districtNo) {
        DialogHelper.showProgressDialog(activity, null, "数据获取中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getDriverAPI().getLocationLL(repertory.getAreaCode(), provinceNo, cityNo, districtNo).enqueue(new Callback<BaseEntity<MapLongAndLatEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<MapLongAndLatEntity>> call, Response<BaseEntity<MapLongAndLatEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.getLocationLL(response.body().getData());
                } else {
                    MToast.showToast(activity.getActivity(), response.message());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<MapLongAndLatEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(activity.getActivity(), t.getMessage());
            }
        });

    }

    public void oneKeyLogin(OneKeyLoginEntity oneKeyLoginEntity) {
        DialogHelper.showProgressDialog(activity, null, "登录中", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().oneClickLogin(oneKeyLoginEntity).enqueue(new Callback<BaseEntity<LoginEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<LoginEntity>> call, Response<BaseEntity<LoginEntity>> response) {

                DialogHelper.dismissProgressDialog();
                if (response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    OneKeyLoginManager.getInstance().finishAuthActivity();
                    if (response.body().getData().isNeedRegister()) {
                        Intent intent = new Intent(activity, SetPwdActivity.class);
                        intent.putExtra("mobile", response.body().getData().getPhone());
                        activity.startActivity(intent);
                    } else {
                        //登录成功逻辑
                        loginImModel(response);

                        /*saveUserInfo(response.body().getData());
                        activity.loginSucceed(response.body().getData(), response.body().getData().getPhone());
                        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, response.body().getData().getToken());
                        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, response.body().getData().getPhone());
                        JPushInterface.setAlias(activity, 1, response.body().getData().getPhone());
                        getUserInfo();*/
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<LoginEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    //网易IM登陆
    private void loginImModel(Response<BaseEntity<LoginEntity>> response) {
//        NimUIKit.login(new LoginInfo(response.body().getData().getImAccount(), response.body().getData().getImToken()), new RequestCallback<LoginInfo>() {
//            @Override
//            public void onSuccess(LoginInfo param) {
                DialogHelper.dismissProgressDialog();
                SharedPreferenceUtil.getInstance().cleatData();
                saveUserInfo(response.body().getData());
                MToast.showToast(activity, "登录成功");
                activity.loginSucceed(response.body().getData(), response.body().getData().getPhone());
                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, response.body().getData().getToken());
                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, response.body().getData().getPhone());
                JPushInterface.setAlias(activity, 1, response.body().getData().getPhone());
                getUserInfo();
//            }
//
//            @Override
//            public void onFailed(int code) {
//                DialogHelper.dismissProgressDialog();
//            }
//
//            @Override
//            public void onException(Throwable exception) {
//                DialogHelper.dismissProgressDialog();
//            }
//        });
    }

    private void saveUserInfo(LoginEntity loginEntity) {
        repertory.saveToken(loginEntity.getToken());
        repertory.saveAccount(loginEntity.getPhone());

//        NimUIKit.setAccount(loginEntity.getImAccount());
//        AVChatKit.setAccount(loginEntity.getImAccount());
        //Preferences.saveUserAccount(loginEntity.getImAccount());
 //       Preferences.saveUserToken(loginEntity.getImToken());
    }

    public void getUserInfo() {
        DialogHelper.showProgressDialog(activity, null, "请求中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().getUserInfo().enqueue(new Callback<BaseEntity<UserMsgEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<UserMsgEntity>> call, Response<BaseEntity<UserMsgEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                if (response.body().getData() == null) return;
                if (response.body().getState().equals("ok")) {
                    activity.getUserMsgSucceed(response.body().getData());
                } else {
                    MToast.showToast(activity, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<UserMsgEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void findCustomerServiceImAccount(String customerServiceContactsId) {
        DialogHelper.showProgressDialog(activity, null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
        Map map = new HashMap();
        map.put("customerServiceContactsId", customerServiceContactsId);
        APIManager.getInstance().getPickAPI().getfindCustomerServiceImAccount(map).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                if (response.body().getState().equals(APIManager.RESPONSE_FAIL)) {
//                    MToast.showToast(activity, response.body().getMsg());
                    activity.checkAllowDialog(response.body().getMsg());
                } else {
                    Object data = response.body().getData(); // 接口返回的是String类型
                    String dataIMid = response.body().getData().toString();
                    IMUtils.getInstance().buildSingleTalking(dataIMid);
//                    NimUIKit.startP2PSession(activity, dataIMid);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });

    }

}
